// 统一管理后端API请求
import axios from 'axios';

// 创建 axios 实例
const axiosInstance = axios.create({
    baseURL: '/api', // 替换为您的 API URL
});

// 添加请求拦截器以附加 token
axiosInstance.interceptors.request.use(config => {
    const token = localStorage.getItem('authToken');
    if (token) {
        config.headers['Authorization'] = `Bearer ${token}`;
    }
    return config;
}, error => {
    console.error('Request Interceptor Error:', error);
    return Promise.reject(error);
});

// 登录
export const login = (userName, password) => {
    return axiosInstance.post('/user/login', {userName, password})
        .then(res => res.data)
        .catch(err => {
            console.log('登录失败', err);
            throw err;
        });
};

// 注册
export const register = (user) => {
    return axiosInstance.post('/user/register', user)
        .then(res => res.data)
        .catch(err => {
            console.log('注册失败', err);
            throw err;
        });
};

// 登出
export const logout = () => {
    return axiosInstance.post('/user/logout')
        .then(res => res.data);
};
//修改密码
export const changePassword = (oldPassword, newPassword) => {
    return axiosInstance.post('/user/change/password', {
        oldPassword,
        newPassword
    });
}
// 获取用户信息
export const getInfo = () => {
    return axiosInstance.get('/user/getInfo')
        .then(res => res.data)
        .catch(err => {
            console.error("获取用户失败", err);
            throw err;
        });
};

// 更新用户信息
export const updateUserInfo = (userInfo) => {
    return axiosInstance.put('/user/updateUserInfo', userInfo)
        .then(res => res.data)
        .catch(err => {
            console.error("更新用户信息失败", err);
            throw err;
        });
};
// 上传头像
export const uploadAvatar = (file) => {
    return axiosInstance.post('/user/common/upload', file)
        .then(res => res.data)
        .catch(err => {
            console.error("上传头像失败", err);
            throw err;
        });
};
// 获取订单状态
export const getOrderStats = () => {
    return axiosInstance.get('/user/orders')
        .then(res => res.data)
        .catch(err => {
            console.error("获取订单状态失败", err);
            throw err;
        });
};

// 获取订单概览
export const getOrderOverview = () => {
    return axiosInstance.get('/user/order/overview')
        .then(res => res.data)
        .catch(err => {
            console.error("获取订单概览失败", err);
            throw err;
        });
};

// 获取订单列表
export const getOrderList = (status) => {
    // 将参数转换为后端需要的格式
    const statusMap = {
        'all': null,
        'ordered': 'CREATED',
        'shipped': 'SHIPPED',
        'picked_up': 'COMPLETED',
        'exception': 'ABNORMAL'
    };

    return axiosInstance.get('/user/orders', {
        params: {
            status: statusMap[status]
        }
    });
};

// 获取地址列表
export const getAddressList = () => {
    return axiosInstance.get('/user/address')
        .then(res => res.data.data)
        .catch(err => {
            console.log('获取地址列表失败', err);
            throw err;
        });
};

// 添加新地址
export const addAddress = (address) => {
    return axiosInstance.post('/user/address/add', address)
        .then(res => res.data)
        .catch(err => {
            console.log('添加地址失败', err);
            throw err;
        });
};

// 更新地址
export const updateAddress = (address) => {
    return axiosInstance.put(`/user/address/updateAddress`, address)
        .then(res => res.data)
        .catch(err => {
            console.log('更新地址失败', err);
            throw err;
        });
};

// 删除地址
export const deleteAddress = (id) => {
    return axiosInstance.delete(`/user/address/${id}`)
        .then(res => res.data)
        .catch(err => {
            console.log('删除地址失败', err);
            throw err;
        });
};
//设置默认地址
export const setDefaultAddress = (id) => {
    return axiosInstance.put(`/user/address/${id}/default`)
}

// 获取快递信息
export const getScanInfo = async (trackingNumber) => {
    return axiosInstance.get(`/user/scan/${trackingNumber}`)
        .then(res => res.data)
        .catch(err => {
            console.error("获取快递信息失败", err);
            throw err;
        });
};

// 更新订单状态
export const updateOrderStatus = (orderId, status) => {
    return axiosInstance.put(`/user/order/${orderId}/status`, {status})
        .then(res => res.data)
        .catch(err => {
            console.error("更新订单状态失败", err);
            throw err;
        });
};

// 确认取件
export const confirmPickup = (orderId) => {
    return axiosInstance.post(`/user/order/${orderId}/pickup`)
        .then(res => res.data)
        .catch(err => {
            console.error("确认取件失败", err);
            throw err;
        });
};

// 处理异常
export const handleException = (orderId) => {
    return axiosInstance.post(`/user/order/${orderId}/exception`)
        .then(res => res.data)
        .catch(err => {
            console.error("处理异常失败", err);
            throw err;
        });
};

// 获取快递柜列表
export const getLockers = () => {
    return axiosInstance.get('/user/lockers') // 假设你的后端有这个接口
        .then(res => res.data)
        .catch(err => {
            console.error('获取快递柜列表失败', err);
            throw err;
        });
};

// 添加取消订单的 API 方法
export const cancelOrder = (orderId) => {
    return axiosInstance.delete(`/user/order/${orderId}`)
        .then(res => res.data)
        .catch(err => {
            console.error("取消订单失败", err);
            throw err;
        });
};

